package com.cn;

import com.cn.pb.BasePb;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;


public class ChannelInitHandler extends ChannelInitializer<SocketChannel>{
	private ChannelIoHandler channelIoHandler;
	
	public ChannelInitHandler(ChannelIoHandler channelIoHandler) {
		this.channelIoHandler = channelIoHandler;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeLine = ch.pipeline();
//		pipeLine.addLast(net.getTrafficHandler());
		pipeLine.addLast("frameEncoder", new LengthFieldPrepender(2));
		pipeLine.addLast("protobufEncoder", new ProtobufEncoder());
		
		pipeLine.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 2, 0, 2));
		pipeLine.addLast("protobufDecoder", new ProtobufDecoder(BasePb.Base.getDefaultInstance(), Global.registry));
		
		pipeLine.addLast("protobufHandler", this.channelIoHandler);
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
		LogHelper.ERROR_LOGGER.error(cause);
		ctx.close();
	}

	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		super.channelUnregistered(ctx);
		LogHelper.CHANNEL_LOGGER.info("监听端口 unregistered:" + Thread.currentThread().getId());
	}

	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
		LogHelper.CHANNEL_LOGGER.info("监听端口 inactive:" + Thread.currentThread().getId());
	}
}